#include "thread.h"

HANDLE ThHandles[0x100];
DWORD ThCount;

void ThInitialize(void) { ThCount = 0; }

HANDLE ThCreateProcessThread(HANDLE hProcess, LPVOID lpEntry) {
  HANDLE hThread;
  LPTHREAD_CONTEXT lpContext;
  LPPROCESS_CONTEXT lpPsContext;
  if (*(HANDLE_TYPE *)hProcess != HANDLE_PROCESS || ThCount > 0x100) {
    return NULL;
  }
  lpPsContext = (LPPROCESS_CONTEXT)hProcess;
  hThread = HeapAllocate(sizeof(struct THREAD_CONTEXT));
  lpContext = (LPTHREAD_CONTEXT)hThread;
  RtlZeroMemory(lpContext, sizeof(struct THREAD_CONTEXT));
  lpContext->Signature = HANDLE_THREAD;
  lpContext->hProcess = hProcess;
  lpContext->cpu.cs = 0x23;
  lpContext->cpu.ds = 0x2B;
  lpContext->cpu.eip = (DWORD)lpEntry;
  lpContext->cpu.eflags |= 0x200;
  lpContext->hPrevThread = hProcess;
  lpContext->hNextThread = lpPsContext->hFirstThread;
  if (lpPsContext->hFirstThread) {
    ((LPTHREAD_CONTEXT)lpPsContext->hFirstThread)->hPrevThread = hThread;
  }
  lpPsContext->hFirstThread = hThread;
  ThHandles[ThCount++] = hThread;
  return hThread;
}
